package com.home.base.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.home.biz.HaomaBiz;
import com.home.biz.LtPhoneBiz;
import com.home.entity.LtPhone;
import com.home.entity.SitePhone;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.stream.Collectors;

/**
 * @author ：chenxf
 * @date ：Created in 2020/6/10 12:45
 * @description：
 * @modified By：
 * @version: $
 */
@Slf4j
public class FetchHaomaUtil implements Callable<String> {

    private HaomaBiz activityBiz;
    /**
     * C002
     * 2003130012433867 -- 一生一号
     * 1910170012348890 --  靓号
     * 1910170012348890 -- 4G飞享18元档
     * 1910230012354413 -- 4G飞享（分销）18元档
     */
    String param="queryPara=#NUM&orderId=#TIME61&queryType=07&qrCodeId=e5af19d2c0594f84b0b2a6779d8903bb&specialIds=1T71T75";
    String  provName="", cityName="",data="",activiName="";
    String url="http://cq.haoma.com/io/5.asp?cnt=50&page_no=1&numcategory=0&klist=#NUM";
    String detailUrl="http://cq.haoma.com/orders/order.asp?id=#ID&hm=#NUM";
    DateTimeFormatter formatter=DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
    String num;
    public FetchHaomaUtil(String data){
        this.num=data;
        this.data=initNum(data);
        System.out.println(this.data.length());

    }
    public FetchHaomaUtil(HaomaBiz activityBiz, String activiName, String num){
        //20200610121240
        this.num=num;
        this.data=initNum(num);
        this.activityBiz=activityBiz;
//        this.provName=provName;
//        this.cityName=cityName;
        // this.acitviCode=acitviCode;
        this.activiName=activiName;
    }

    public String initNum(String num){
        return new StringBuilder().append( StringUtils.rightPad("1",11-num.length(),"_")).append(num).toString();
    }


    public void save() {
        try {
            activityBiz.saveList(fetch());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public List<SitePhone> fetch() throws Exception {
        log.debug("fetch data"+data);
        String doc = Jsoup.connect(url.replace("#NUM",data))
                .ignoreContentType(true)
                .method(Connection.Method.GET)
                .header("Content-Type","application/json;charset=UTF-8")
                .execute()
                .body();
       String[] array=doc.split("\\|");
       List<SitePhone> phones=new ArrayList<>();
       for(String numStr: array){
           String[] nums=numStr.split(",");
           if(nums.length<7){
               continue;
           }
           String numCompany="无";
           if(nums[2].equals("0")){
               numCompany="重庆移动";
           }else if (nums[2].equals("1")){
               numCompany="重庆联通";
           }else if (nums[2].equals("2")){
               numCompany="重庆电信";
           }
           BigDecimal total=new BigDecimal(nums[3]).add(new BigDecimal(nums[4]));
           phones.add(SitePhone.builder().phoneNum(nums[0]).companyName(numCompany).conditionName(num).fetchMethod(activiName).notes(fetchDetail(nums[6],nums[0])).price(total.toString()).money(nums[4]).build());
       }

        return phones;
    }

    public String  fetchDetail(String id,String num){
        try {
            //Document document= Jsoup.parse(new URL("https://www.baidu.com"),1000);

            Document doc = Jsoup.connect(detailUrl.replace("#NUM",num).replace("#ID",id))
                    .ignoreContentType(true)

                    .method(Connection.Method.GET)
                    .header("Content-Type","application/json;charset=UTF-8")
                    // .header("tokenCode",tokenCode)
                    // .userAgent("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)")
                    // .cookies(cookie) /ul:eq(2)/li/span:eq(2)
                   .get();
            //System.out.println(doc.body());
            Elements info = doc.select("div.page>form>.registItems:eq(1)>li>.cell>span");
            //System.out.println(info.text());
            return info.text();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String call() throws Exception {
        save();
        return data+"fetch finish";
    }

    public static void main(String[] args){
        String num="9271";
        //num
        System.out.println(num.length());
        FetchHaomaUtil fetchNumUtil=new FetchHaomaUtil( num);
        try {
            //fetchNumUtil.fetchDetail("30946521","18996112972");
            List<SitePhone> result=fetchNumUtil.fetch();
           System.out.println(result.size());
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
